package com.crealth.handler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crealth.ConstantDefine;
import com.crealth.Result.DayKpiSignedResult;
import com.crealth.Result.FollowupConsumerResult;
import com.crealth.db.ConsumerDb;
import com.crealth.db.ConsumerProductDb;
import com.crealth.db.StaffDayKPIDb;
import com.crealth.db.UserDb;
import com.crealth.memcached.UserCached;
import com.crealth.model.StaffDayKPIModel;
import com.crealth.model.UserModel;
import com.crealth.msg.NetMessageData;
import com.crealth.utils.StringUtil;

public class StaffKPIHandler {
	//private static Logger logger = Logger.getLogger("running_log");
	private static Logger errorLog = Logger.getLogger("error_log");
	
	public static NetMessageData checkDayKPI(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		Integer userID = msgJson.getIntValue("id");
		if (userID <= 0) {
			return null;
		}
		Integer userPos = UserDb.selectUserPosition(userID);
		if (userPos < ConstantDefine.Team_Manager ) {
			errorLog.error("userID: "+ userID+" checkDayKPI limited authority");
			return null;			
		}
		List<Integer> underlingIDs = null;
		if (ConstantDefine.Team_Manager == userPos ) {
			underlingIDs = UserDb.selectUnderlingIDs(userID);
			if (underlingIDs.indexOf(userID) < 0) {
				underlingIDs.add(userID);
			}
		}
		else if (userPos == ConstantDefine.Branch_Mgr || userPos == ConstantDefine.Branch_Mgr_Fu) {
			underlingIDs = UserDb.selectUnderlingIDs(userID);
		}
		else if (userPos >= ConstantDefine.Head_Manager) {
			underlingIDs = UserDb.selectAllSalesManAndTeamMgrIDs();
		}
		if (underlingIDs == null || underlingIDs.size() == 0) {
			resJson.put("cnt", 0);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		String strSearchDay = msgJson.getString("searchDay");
		Date curDate = new Date(System.currentTimeMillis());
    	String strtoday = new SimpleDateFormat("yyyy-MM-dd").format(curDate);
		String strids = StringUtil.mergeListIntegerToString(underlingIDs, ",");
		List<StaffDayKPIModel> kpils = null;
		if (strSearchDay.equals(strtoday)) {
			kpils = StaffDayKPIDb.selectToDayKPI(strids);
		}
		else {
			kpils = StaffDayKPIDb.selectUnderlingDayKPI(strids, strSearchDay);
		}
		
		Map<Integer, Integer> userIDHasKPI = new HashMap<Integer, Integer>();
		for (StaffDayKPIModel kpi : kpils) {
			int uID = kpi.getUserID();
			userIDHasKPI.put(uID, 1);
		}		
		for (Integer underlingID : underlingIDs) {
			if (!userIDHasKPI.containsKey(underlingID)) {
				UserModel curUser = UserCached.selectUserByID(underlingID);
				if (curUser != null && curUser.getStaffStatus() != 6 ) {
					StaffDayKPIModel tempKpi = new StaffDayKPIModel(underlingID);
					kpils.add(tempKpi);
				}
			}
		}
		
		List<DayKpiSignedResult> signedResultls = ConsumerProductDb.selectConsumerSignedResultBySignedTime(strSearchDay);
		Map<Integer, Integer> userSignedMap = new HashMap<Integer, Integer>();
		Map<Integer, String> userSignedConsumerIDsMap = new HashMap<Integer, String>(); 
		for (DayKpiSignedResult product : signedResultls) {
			String productNo = product.getProductNo();
			if (productNo.indexOf("-") > 0) {
				continue;
			}
			Integer productUserID = product.getUserID();
			if (userSignedMap.containsKey(productUserID)) {
				Integer value = userSignedMap.get(productUserID);
				userSignedMap.put(productUserID, value+1);
			} else {
				userSignedMap.put(productUserID, 1);
			}
			String strConsumerID = "" + product.getConsumerID();
			if (userSignedConsumerIDsMap.containsKey(productUserID)) {
				String strValue = userSignedConsumerIDsMap.get(productUserID);
				strValue += ("," + strConsumerID);
				userSignedConsumerIDsMap.put(productUserID, strValue);
			} else {
				userSignedConsumerIDsMap.put(productUserID, strConsumerID);
			}
		}
		List<DayKpiSignedResult> extendLoanProductls = ConsumerProductDb.selectConsumerResultByExtendLoanTime(strSearchDay);
		Map<Integer, Integer> userExtendLoanMap = new HashMap<Integer, Integer>();
		Map<Integer, String> extendLoanConsumerIDsMap = new HashMap<Integer, String>();
		for (DayKpiSignedResult product : extendLoanProductls) {
			Integer productUserID = product.getUserID();
			int bankExtendLoan = Integer.valueOf(product.getBankExtendLoan());
			if (userExtendLoanMap.containsKey(productUserID)) {
				Integer value = userExtendLoanMap.get(productUserID);
				userExtendLoanMap.put(productUserID, value+bankExtendLoan);
			} else {
				userExtendLoanMap.put(productUserID, bankExtendLoan);
			}
			String strConsumerID = "" + product.getConsumerID();
			if (extendLoanConsumerIDsMap.containsKey(productUserID)) {
				String strValue = extendLoanConsumerIDsMap.get(productUserID);
				strValue += ("," + strConsumerID);
				extendLoanConsumerIDsMap.put(productUserID, strValue);
			} else {
				extendLoanConsumerIDsMap.put(productUserID, strConsumerID);
			}
		}		
			
		List<FollowupConsumerResult> followupls = ConsumerDb.selectStatisticsFollowup(strSearchDay, strids);
		Map<Integer, Integer> userFollowupMap = new HashMap<Integer, Integer>();
		for (FollowupConsumerResult followupResult : followupls) {
			Integer followupUserID = followupResult.getUserID();
			if (userFollowupMap.containsKey(followupUserID)) {
				Integer value = userFollowupMap.get(followupUserID);
				userFollowupMap.put(followupUserID, value+1);
			} else {
				userFollowupMap.put(followupUserID, 1);
			}			
		}
		
		JSONArray jsonArray = new JSONArray();
		int cnt = kpils.size();
		for (StaffDayKPIModel kpi : kpils) {
			Integer kpiUserID = kpi.getUserID();
			if (userSignedMap.containsKey(kpiUserID)) {
				int signedNum = userSignedMap.get(kpiUserID);
				kpi.setSignedNum(signedNum);
			} else {
				kpi.setSignedNum(0);
			}
			if (userExtendLoanMap.containsKey(kpiUserID)) {
				int extendLoanNum = userExtendLoanMap.get(kpiUserID);
				kpi.setExtendLoanNum(extendLoanNum);
			} else {
				kpi.setExtendLoanNum(0);
			}
			if (userFollowupMap.containsKey(kpiUserID)) {
				int followupNum = userFollowupMap.get(kpiUserID);
				kpi.setFollowupNum(followupNum);
			} else {
				kpi.setFollowupNum(0);
			}
			if (userSignedConsumerIDsMap.containsKey(kpiUserID)) {
				String signedConsumerIDs = userSignedConsumerIDsMap.get(kpiUserID);
				kpi.setSignedConsumerIDs(signedConsumerIDs);
			} else {
				kpi.setSignedConsumerIDs("");
			}
			if (extendLoanConsumerIDsMap.containsKey(kpiUserID)) {
				String extendLoanConsumerIDs = extendLoanConsumerIDsMap.get(kpiUserID);
				kpi.setExtendLoanConsumerIDs(extendLoanConsumerIDs);
			} else {
				kpi.setExtendLoanConsumerIDs("");
			}
			JSONObject jsonValue = kpi.toJSONObject();
			jsonArray.add(jsonValue);
		}
		
		resJson.put("cnt", cnt);
		resJson.put("day", strSearchDay);
		resJson.put("dayKpils", jsonArray);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	
}
